<script lang="ts" setup>
import PageHeader from '../../../../components/page-header.vue';
import { generateCssVars } from '@vc/utils';
import { INIT_TAB_STYLE } from '../../constants';
import { INIT_PARAMS, PAGE_SIZE } from '../../../../constants';
import { useTable } from './useTable';
import { useF9Context } from '@/views/modules/enterprise/use/use-context';
import { getGreenBondF9, type IGreenBond } from '@/views/modules/enterprise/apis';

interface Props {
  title: string;
  menuId: string;
}

const { title, menuId } = defineProps<Props>();
const { companyId } = useF9Context();

const requestParams = reactive<IGreenBond>({
  companyId,
  maturityType: 1,
  pageNum: 1,
  ...INIT_PARAMS
});

const totalNum = ref(0);
let tableData = $ref<any[]>([]);
let isFirstLoad = $ref(true);

const { run, loading, error } = useRequest(getGreenBondF9, {
  defaultParams: [requestParams],
  onSuccess: (data) => {
    totalNum.value = data?.total;
    tableData = data?.values;

    if (isFirstLoad && !tableData?.length && requestParams.maturityType === 1) {
      requestParams.maturityType = 2;
    } else if (isFirstLoad && !tableData?.length && requestParams.maturityType === 2) {
      requestParams.maturityType = 1;
    }
    isFirstLoad && tableData?.length ? (isFirstLoad = false) : '';
  }
});

const { columns } = useTable();

const tabMap = reactive([
  { name: '存续中', code: 1 },
  { name: '已到期', code: 2 }
]);

const handleTabChange = (tabCode: number) => {
  requestParams.maturityType = tabCode;
  requestParams.pageNum = 1;
};

watch(
  () => requestParams,
  () => {
    run(requestParams);
  },
  { deep: true }
);
</script>
<template>
  <page-header class="mt-18px mb-15px" :title="title" :menuId="menuId" is-small />
  <vc-empty-fail @click="run(requestParams)" v-if="error" />
  <div class="container" v-else>
    <div class="tabs" :style="generateCssVars(INIT_TAB_STYLE, 'tabs')">
      <vc-tabs :model-value="requestParams.maturityType" @tab-change="handleTabChange">
        <vc-tab-pane v-for="(item, index) in tabMap" :key="index" :label="item.name" :name="item.code" />
      </vc-tabs>
    </div>
    <vc-table :loading="loading" :tableData="tableData" :columns="columns" :total="totalNum" :pageSize="PAGE_SIZE" v-model:pageNum="requestParams.pageNum" />
  </div>
</template>
